/**
 * 微信登录调试工具
 */

// 调试模式开关
const DEBUG_MODE = process.env.NODE_ENV === 'development'

/**
 * 调试日志工具
 */
export class WechatDebugger {
  private static logs: Array<{
    timestamp: string
    level: 'info' | 'warn' | 'error'
    message: string
    data?: any
  }> = []

  /**
   * 记录调试信息
   */
  static log(level: 'info' | 'warn' | 'error', message: string, data?: any) {
    const logEntry = {
      timestamp: new Date().toISOString(),
      level,
      message,
      data,
    }

    this.logs.push(logEntry)

    // 只在开发模式下输出到控制台
    if (DEBUG_MODE) {
      const prefix = `[WX-LOGIN-${level.toUpperCase()}]`
      switch (level) {
        case 'info':
          console.log(prefix, message, data || '')
          break
        case 'warn':
          console.warn(prefix, message, data || '')
          break
        case 'error':
          console.error(prefix, message, data || '')
          break
      }
    }

    // 保持日志数量在合理范围内
    if (this.logs.length > 100) {
      this.logs = this.logs.slice(-50)
    }
  }

  /**
   * 获取所有日志
   */
  static getLogs() {
    return [...this.logs]
  }

  /**
   * 清空日志
   */
  static clearLogs() {
    this.logs = []
  }

  /**
   * 导出日志
   */
  static exportLogs() {
    const logsText = this.logs
      .map(log => `[${log.timestamp}] ${log.level.toUpperCase()}: ${log.message}${log.data ? ` ${JSON.stringify(log.data)}` : ''}`)
      .join('\n')

    return logsText
  }

  /**
   * 检查微信环境
   */
  static checkWechatEnvironment() {
    const info = {
      isWechat: false,
      platform: '',
      version: '',
      canUseGetUserProfile: false,
      canUseLogin: false,
    }

    // #ifdef MP-WEIXIN
    try {
      const systemInfo = uni.getSystemInfoSync()
      info.isWechat = true
      info.platform = systemInfo.platform
      info.version = systemInfo.version

      // 检查API可用性
      info.canUseGetUserProfile = typeof uni.getUserProfile === 'function'
      info.canUseLogin = typeof uni.login === 'function'

      this.log('info', '微信环境检查', info)
    }
    catch (error) {
      this.log('error', '获取微信环境信息失败', error)
    }
    // #endif

    // #ifndef MP-WEIXIN
    info.isWechat = false
    this.log('warn', '非微信小程序环境')
    // #endif

    return info
  }

  /**
   * 检查网络状态
   */
  static async checkNetworkStatus() {
    try {
      const networkInfo = await new Promise((resolve, reject) => {
        uni.getNetworkType({
          success: resolve,
          fail: reject,
        })
      })

      this.log('info', '网络状态检查', networkInfo)
      return networkInfo
    }
    catch (error) {
      this.log('error', '获取网络状态失败', error)
      return null
    }
  }

  /**
   * 检查存储状态
   */
  static checkStorageStatus() {
    try {
      const storageInfo = {
        token: uni.getStorageSync('token'),
        userInfo: uni.getStorageSync('userInfo'),
        wechatOpenid: uni.getStorageSync('wechat_openid'),
      }

      // 不记录敏感信息的完整内容
      const logInfo = {
        hasToken: !!storageInfo.token,
        hasUserInfo: !!storageInfo.userInfo,
        hasWechatOpenid: !!storageInfo.wechatOpenid,
        tokenLength: storageInfo.token ? storageInfo.token.length : 0,
      }

      this.log('info', '存储状态检查', logInfo)
      return storageInfo
    }
    catch (error) {
      this.log('error', '检查存储状态失败', error)
      return null
    }
  }

  /**
   * 测试API连通性
   */
  static async testApiConnectivity() {
    try {
      this.log('info', '开始测试API连通性')

      // 测试基础连通性
      const response = await new Promise((resolve, reject) => {
        uni.request({
          url: '/app-api/reading/auth/test', // 假设有一个测试接口
          method: 'GET',
          timeout: 5000,
          success: resolve,
          fail: reject,
        })
      })

      this.log('info', 'API连通性测试成功', response)
      return true
    }
    catch (error) {
      this.log('error', 'API连通性测试失败', error)
      return false
    }
  }

  /**
   * 完整的环境检查
   */
  static async performFullCheck() {
    this.log('info', '开始完整环境检查')

    const results = {
      wechatEnv: this.checkWechatEnvironment(),
      networkStatus: await this.checkNetworkStatus(),
      storageStatus: this.checkStorageStatus(),
      apiConnectivity: await this.testApiConnectivity(),
    }

    this.log('info', '完整环境检查完成', results)
    return results
  }
}

/**
 * 微信登录流程跟踪器
 */
export class WechatLoginTracker {
  private static currentSession: string | null = null
  private static steps: Array<{
    sessionId: string
    step: string
    timestamp: string
    success: boolean
    data?: any
    error?: any
  }> = []

  /**
   * 开始新的登录会话
   */
  static startSession() {
    this.currentSession = `wx_login_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    WechatDebugger.log('info', `开始新的登录会话: ${this.currentSession}`)
    return this.currentSession
  }

  /**
   * 记录登录步骤
   */
  static trackStep(step: string, success: boolean, data?: any, error?: any) {
    if (!this.currentSession) {
      this.startSession()
    }

    const stepRecord = {
      sessionId: this.currentSession!,
      step,
      timestamp: new Date().toISOString(),
      success,
      data,
      error,
    }

    this.steps.push(stepRecord)

    const logLevel = success ? 'info' : 'error'
    const logMessage = `登录步骤 [${step}] ${success ? '成功' : '失败'}`
    WechatDebugger.log(logLevel, logMessage, error || data)

    // 保持步骤记录在合理范围内
    if (this.steps.length > 200) {
      this.steps = this.steps.slice(-100)
    }
  }

  /**
   * 结束当前会话
   */
  static endSession(success: boolean) {
    if (this.currentSession) {
      WechatDebugger.log('info', `登录会话结束: ${this.currentSession}, 结果: ${success ? '成功' : '失败'}`)
      this.currentSession = null
    }
  }

  /**
   * 获取当前会话的步骤
   */
  static getCurrentSessionSteps() {
    if (!this.currentSession)
      return []
    return this.steps.filter(step => step.sessionId === this.currentSession)
  }

  /**
   * 获取所有步骤
   */
  static getAllSteps() {
    return [...this.steps]
  }

  /**
   * 清空步骤记录
   */
  static clearSteps() {
    this.steps = []
    this.currentSession = null
  }
}

/**
 * 微信登录性能监控
 */
export class WechatLoginPerformance {
  private static timers: Map<string, number> = new Map()

  /**
   * 开始计时
   */
  static startTimer(name: string) {
    this.timers.set(name, Date.now())
    WechatDebugger.log('info', `开始计时: ${name}`)
  }

  /**
   * 结束计时
   */
  static endTimer(name: string) {
    const startTime = this.timers.get(name)
    if (startTime) {
      const duration = Date.now() - startTime
      this.timers.delete(name)
      WechatDebugger.log('info', `计时结束: ${name}, 耗时: ${duration}ms`)
      return duration
    }
    return 0
  }

  /**
   * 记录性能指标
   */
  static recordMetric(name: string, value: number, unit: string = 'ms') {
    WechatDebugger.log('info', `性能指标: ${name} = ${value}${unit}`)
  }
}

// 便捷方法导出
export function debugLog(level: 'info' | 'warn' | 'error', message: string, data?: any) {
  WechatDebugger.log(level, message, data)
}

export function trackLoginStep(step: string, success: boolean, data?: any, error?: any) {
  WechatLoginTracker.trackStep(step, success, data, error)
}

export function startLoginSession() {
  return WechatLoginTracker.startSession()
}

export function endLoginSession(success: boolean) {
  WechatLoginTracker.endSession(success)
}

export function startPerformanceTimer(name: string) {
  WechatLoginPerformance.startTimer(name)
}

export function endPerformanceTimer(name: string) {
  return WechatLoginPerformance.endTimer(name)
}

// 全局调试信息收集
export async function collectDebugInfo() {
  const debugInfo = {
    timestamp: new Date().toISOString(),
    environment: WechatDebugger.checkWechatEnvironment(),
    network: await WechatDebugger.checkNetworkStatus(),
    storage: WechatDebugger.checkStorageStatus(),
    logs: WechatDebugger.getLogs(),
    loginSteps: WechatLoginTracker.getAllSteps(),
  }

  return debugInfo
}

// 导出调试报告
export async function exportDebugReport() {
  const debugInfo = await collectDebugInfo()
  const report = `
# 微信登录调试报告

## 生成时间
${debugInfo.timestamp}

## 环境信息
${JSON.stringify(debugInfo.environment, null, 2)}

## 网络状态
${JSON.stringify(debugInfo.network, null, 2)}

## 存储状态
${JSON.stringify(debugInfo.storage, null, 2)}

## 调试日志
${WechatDebugger.exportLogs()}

## 登录步骤
${debugInfo.loginSteps.map(step =>
  `[${step.timestamp}] ${step.step}: ${step.success ? '成功' : '失败'}${step.error ? ` - ${JSON.stringify(step.error)}` : ''}`,
).join('\n')}
`

  return report
}
